import {
  ADD_CAR,
  CarAction,
  ADD_CAR_COUNT,
  SUB_CAR_COUNT,
  DELETE_CAR,
  SWITCH_CAR_CHECK,
} from "./carActions";
interface CarState {
  carList: CarItem[];
}

export interface CarItem {
  id: string;
  price: string | number;
  url: string;
  title: string;
  count: number;
  checked: boolean;
}

const initState: CarState = {
  carList: [],
};

export const carReducer = (state = initState, action: CarAction) => {
  switch (action.type) {
    case ADD_CAR: {
      const item = state.carList.find((v) => action.payload.id === v.id);
      if (item) {
        item.count++;
      } else {
        state.carList.unshift(action.payload);
      }

      return {
        ...state,
        carList: [...state.carList],
      };
    }
    case ADD_CAR_COUNT: {
      const item = state.carList.find((v) => action.payload === v.id);
      if (item) item.count++;
      return {
        ...state,
        carList: [...state.carList],
      };
    }
    case SUB_CAR_COUNT: {
      const item = state.carList.find((v) => action.payload === v.id);
      if (item) item.count--;
      return {
        ...state,
        carList: [...state.carList],
      };
    }
    case DELETE_CAR: {
      const newCarList = state.carList.filter((v) => v.id !== action.payload);
      return {
        ...state,
        carList: newCarList,
      };
    }
    case SWITCH_CAR_CHECK: {
      const item = state.carList.find((v) => v.id === action.payload);
      if (item) item.checked = !item.checked;
      return {
        ...state,
        carList: [...state.carList],
      };
    }
    default:
      return state;
  }
};
